package com.wjk.kylin.modules.generator.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wjk.kylin.core.common.controller.BaseController;
import com.wjk.kylin.core.common.data.RequestData;
import com.wjk.kylin.core.common.data.ResponseData;
import com.wjk.kylin.core.exception.BusinessException;
import com.wjk.kylin.core.utils.DateUtils;
import com.wjk.kylin.core.utils.PageUtils;
import com.wjk.kylin.modules.generator.entity.GenTable;
import com.wjk.kylin.modules.generator.entity.GenTableColumn;
import com.wjk.kylin.modules.generator.service.IGenTableColumnService;
import com.wjk.kylin.modules.generator.service.IGenTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  代码生成 前端控制器
 * </p>
 *
 * @author wangjkui
 * @since 2020-08-29
 */
@Slf4j
@Api("代码生成")
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {
    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    @PreAuthorize("hasAuthority('tool:gen:list')")
    @ApiOperation("列表")
    @GetMapping("/list")
    public ResponseData list(GenTable genTable) {
        IPage<GenTable> page = genTableService.findPage(new RequestData<GenTable>(), genTable);

        return ResponseData.success().data("page", new PageUtils(page));
    }

    @PreAuthorize("hasAuthority('tool:gen:query')")
    @ApiOperation("详情")
    @GetMapping("/{tableId}")
    public ResponseData get(@PathVariable String tableId) {
        GenTable table = genTableService.getById(tableId);

        return ResponseData.success().data("table", table);
    }

    @PreAuthorize("hasAuthority('tool:gen:list')")
    @ApiOperation("数据库列表")
    @GetMapping("/db/list")
    public ResponseData dataList(GenTable genTable) {
        IPage<GenTable> page = genTableService.findDbPage(new RequestData<GenTable>(), genTable);
        return ResponseData.success().data("page", new PageUtils(page));
    }

    @PreAuthorize("hasAuthority('tool:gen:list')")
    @ApiOperation("数据表字段列表")
    @GetMapping(value = "/column/{tableId}")
    public ResponseData columnList(@PathVariable String tableId) {
        List<GenTableColumn> list = genTableColumnService.findListByTableId(tableId);

        return ResponseData.success().data("list", list).data("total",list.size());
    }

    @PreAuthorize("hasAuthority('tool:gen:list')")
    @ApiOperation("导入表结构")
    @PostMapping("/importTable/{tableNames}")
    public ResponseData importTableSave(@PathVariable String[] tableNames) {
        genTableService.importGenTable(tableNames);

        return ResponseData.success();
    }

    @PreAuthorize("hasAuthority('tool:gen:edit')")
    @ApiOperation("编辑")
    @PutMapping
    public ResponseData update(@Validated @RequestBody GenTable genTable) {
        boolean flag =  genTableService.update(genTable);
        if (flag) {
            return ResponseData.success();
        } else {
            return ResponseData.error("编辑失败");
        }
    }

    @ApiOperation("删除")
    @PreAuthorize("hasAuthority('tool:gen:remove')")
    @DeleteMapping("/{tableIds}")
    public ResponseData remove(@PathVariable String[] tableIds) {
        boolean flag = genTableService.deleteByIds(tableIds);
        if (flag) {
            return ResponseData.success();
        } else {
            return ResponseData.error("删除失败");
        }
    }

    @ApiOperation("预览代码")
    @PreAuthorize("hasAuthority('tool:gen:preview')")
    @GetMapping("/preview/{tableId}")
    public ResponseData preview(@PathVariable("tableId") String tableId){
        Map<String, Object> dataMap = genTableService.previewCode(tableId);

        return ResponseData.success().data(dataMap);
    }

//    @ApiOperation("生成代码（下载方式）")
//    @PreAuthorize("hasAuthority('tool:gen:code')")
//    @GetMapping("/download/{tableName}")
//    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName){
//
//        byte[] data = genTableService.downloadCode(tableName);
//
//        genCode(response, data);
//    }

//    @ApiOperation("生成代码（自定义路径）")
//    @PreAuthorize("hasAuthority('tool:gen:code')")
//    @GetMapping("/genCode/{tableNames}")
//    public ResponseData genCode(HttpServletResponse response, @PathVariable("tableNames")[] String tableName) {
//
//        genTableService.generatorCode(tableName);
//
//        return ResponseData.success();
//    }

    @ApiOperation("生成代码（zip下载）")
    @PreAuthorize("hasAuthority('tool:gen:code')")
    @GetMapping("/batchGenCode/{tableNames}")
    public void batchGenCode(HttpServletResponse response, @PathVariable("tableNames") String[] tableNames) {
        byte[] data = genTableService.downloadCode(tableNames);

        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data){
        try {
            String filename = DateUtils.formatDate(new Date(),"yyyyMMddHHmmss")+".zip";
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename="+filename);
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        }catch (Exception e){
            log.error("生成zip文件异常",e);
            throw new BusinessException("生成zip文件异常，请重试");
        }

    }
}